<template>
  <div class="settings-container">
    <div class="page-header">
      <h2 class="page-title">系统设置</h2>
    </div>
    
    <el-tabs v-model="activeTab" class="settings-tabs">
      <el-tab-pane label="基本设置" name="basic">
        <div class="settings-form-container">
          <el-form 
            ref="basicFormRef" 
            :model="basicForm" 
            :rules="basicRules" 
            label-width="140px"
            class="settings-form"
          >
            <el-form-item label="系统名称" prop="systemName">
              <el-input v-model="basicForm.systemName" placeholder="请输入系统名称" />
            </el-form-item>
            <el-form-item label="系统Logo">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeLogoUpload"
                :http-request="handleLogoUpload"
              >
                <img v-if="basicForm.logoUrl" :src="basicForm.logoUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">建议尺寸: 120px * 40px, 格式: JPG/PNG</div>
            </el-form-item>
            <el-form-item label="系统简介" prop="description">
              <el-input 
                v-model="basicForm.description" 
                type="textarea" 
                :rows="3"
                placeholder="请输入系统简介" 
              />
            </el-form-item>
            <el-form-item label="管理员邮箱" prop="adminEmail">
              <el-input v-model="basicForm.adminEmail" placeholder="请输入管理员邮箱" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="basicForm.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="系统版本">
              <el-tag>v{{ basicForm.version }}</el-tag>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBasicSettings">保存设置</el-button>
              <el-button @click="resetBasicForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="业务设置" name="business">
        <div class="settings-form-container">
          <el-form 
            ref="businessFormRef" 
            :model="businessForm" 
            :rules="businessRules" 
            label-width="180px"
            class="settings-form"
          >
            <el-form-item label="每日最大叫号人数" prop="maxDailyTickets">
              <el-input-number 
                v-model="businessForm.maxDailyTickets" 
                :min="50" 
                :max="1000" 
              />
              <span class="form-tip">设置为0表示不限制</span>
            </el-form-item>
            <el-form-item label="业务办理时间" prop="businessHours">
              <el-time-picker
                v-model="businessForm.startTime"
                format="HH:mm"
                placeholder="开始时间"
              />
              <span class="time-separator">至</span>
              <el-time-picker
                v-model="businessForm.endTime"
                format="HH:mm"
                placeholder="结束时间"
              />
            </el-form-item>
            <el-form-item label="工作日设置">
              <el-checkbox-group v-model="businessForm.workDays">
                <el-checkbox label="1">周一</el-checkbox>
                <el-checkbox label="2">周二</el-checkbox>
                <el-checkbox label="3">周三</el-checkbox>
                <el-checkbox label="4">周四</el-checkbox>
                <el-checkbox label="5">周五</el-checkbox>
                <el-checkbox label="6">周六</el-checkbox>
                <el-checkbox label="0">周日</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="启用人脸识别" prop="enableFaceRecognition">
              <el-switch v-model="businessForm.enableFaceRecognition" />
              <span class="form-tip">开启后自助取号需要进行人脸识别</span>
            </el-form-item>
            <el-form-item label="人脸匹配阈值" prop="faceMatchThreshold" v-if="businessForm.enableFaceRecognition">
              <el-slider 
                v-model="businessForm.faceMatchThreshold" 
                :min="60" 
                :max="95" 
                :format-tooltip="formatThreshold"
              />
              <span class="form-tip">数值越高，匹配要求越严格</span>
            </el-form-item>
            <el-form-item label="重复取号限制" prop="ticketIntervalMinutes">
              <el-input-number 
                v-model="businessForm.ticketIntervalMinutes" 
                :min="0" 
                :max="1440"
              />
              <span class="form-tip">同一身份证/手机号多少分钟内不能重复取号，0表示不限制</span>
            </el-form-item>
            <el-form-item label="叫号等待超时时间" prop="callTimeoutMinutes">
              <el-input-number 
                v-model="businessForm.callTimeoutMinutes" 
                :min="1" 
                :max="30"
              />
              <span class="form-tip">单位: 分钟，超过此时间未到窗口办理则自动标记为过号</span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBusinessSettings">保存设置</el-button>
              <el-button @click="resetBusinessForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="短信设置" name="sms">
        <div class="settings-form-container">
          <el-form 
            ref="smsFormRef" 
            :model="smsForm" 
            :rules="smsRules" 
            label-width="140px"
            class="settings-form"
          >
            <el-form-item label="启用短信通知" prop="enableSms">
              <el-switch v-model="smsForm.enableSms" />
            </el-form-item>
            
            <template v-if="smsForm.enableSms">
              <el-form-item label="短信服务提供商" prop="smsProvider">
                <el-select v-model="smsForm.smsProvider" placeholder="请选择短信服务提供商">
                  <el-option label="阿里云" value="aliyun" />
                  <el-option label="腾讯云" value="tencent" />
                  <el-option label="华为云" value="huawei" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="AccessKey" prop="accessKey">
                <el-input v-model="smsForm.accessKey" placeholder="请输入AccessKey" />
              </el-form-item>
              
              <el-form-item label="AccessSecret" prop="accessSecret">
                <el-input 
                  v-model="smsForm.accessSecret" 
                  placeholder="请输入AccessSecret" 
                  show-password
                />
              </el-form-item>
              
              <el-form-item label="签名" prop="signName">
                <el-input v-model="smsForm.signName" placeholder="请输入短信签名" />
              </el-form-item>
              
              <el-form-item label="取号成功模板ID" prop="ticketTemplateId">
                <el-input v-model="smsForm.ticketTemplateId" placeholder="请输入取号成功模板ID" />
              </el-form-item>
              
              <el-form-item label="叫号通知模板ID" prop="callTemplateId">
                <el-input v-model="smsForm.callTemplateId" placeholder="请输入叫号通知模板ID" />
              </el-form-item>
              
              <el-divider content-position="left">模板测试</el-divider>
              
              <el-form-item label="测试手机号" prop="testPhone">
                <el-input v-model="smsForm.testPhone" placeholder="请输入测试手机号" />
              </el-form-item>
              
              <el-form-item>
                <el-button @click="testTicketSms">测试取号短信</el-button>
                <el-button @click="testCallSms">测试叫号短信</el-button>
              </el-form-item>
            </template>
            
            <el-form-item>
              <el-button type="primary" @click="saveSmsSettings">保存设置</el-button>
              <el-button @click="resetSmsForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="系统备份" name="backup">
        <div class="settings-form-container">
          <el-form 
            ref="backupFormRef" 
            :model="backupForm" 
            label-width="180px"
            class="settings-form"
          >
            <el-form-item label="启用自动备份" prop="enableAutoBackup">
              <el-switch v-model="backupForm.enableAutoBackup" />
            </el-form-item>
            
            <template v-if="backupForm.enableAutoBackup">
              <el-form-item label="备份频率" prop="backupFrequency">
                <el-select v-model="backupForm.backupFrequency" placeholder="请选择备份频率">
                  <el-option label="每天" value="daily" />
                  <el-option label="每周" value="weekly" />
                  <el-option label="每月" value="monthly" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="备份时间" prop="backupTime">
                <el-time-picker
                  v-model="backupForm.backupTime"
                  format="HH:mm"
                  placeholder="选择时间"
                />
                <span class="form-tip">系统在该时间点自动执行备份</span>
              </el-form-item>
              
              <el-form-item label="保留备份数量" prop="maxBackupCount">
                <el-input-number 
                  v-model="backupForm.maxBackupCount" 
                  :min="1" 
                  :max="30"
                />
                <span class="form-tip">超过数量时会自动删除最旧的备份</span>
              </el-form-item>
            </template>
            
            <el-divider content-position="left">备份记录</el-divider>
            
            <el-table 
              :data="backupRecords" 
              style="width: 100%; margin-bottom: 20px" 
              border
            >
              <el-table-column prop="fileName" label="备份文件" min-width="200" />
              <el-table-column prop="createTime" label="备份时间" width="180" />
              <el-table-column prop="fileSize" label="文件大小" width="120" />
              <el-table-column prop="type" label="备份类型" width="120">
                <template #default="scope">
                  <el-tag :type="scope.row.type === 'auto' ? 'success' : 'primary'">
                    {{ scope.row.type === 'auto' ? '自动备份' : '手动备份' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="small" @click="downloadBackup(scope.row)">下载</el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="deleteBackup(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <el-form-item>
              <el-button type="primary" @click="createManualBackup">
                <el-icon><Tickets /></el-icon>创建备份
              </el-button>
              <el-button type="primary" @click="saveBackupSettings">保存设置</el-button>
              <el-button @click="resetBackupForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Tickets } from '@element-plus/icons-vue'

export default {
  name: 'SystemConfig',
  components: {
    Plus,
    Tickets
  },
  setup() {
    const activeTab = ref('basic')
    
    // 基本设置
    const basicFormRef = ref(null)
    const basicFormState = reactive({
      basicForm: {
        systemName: '智能人脸识别排队叫号系统',
        logoUrl: 'https://via.placeholder.com/120x40',
        description: '基于人脸识别技术的智能排队叫号系统，提供自助取号、智能叫号、业务统计等功能。',
        adminEmail: 'admin@example.com',
        contactPhone: '400-123-4567',
        version: '1.2.3'
      },
      basicRules: {
        systemName: [
          { required: true, message: '请输入系统名称', trigger: 'blur' },
          { max: 30, message: '长度不能超过30个字符', trigger: 'blur' }
        ],
        adminEmail: [
          { required: true, message: '请输入管理员邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^[0-9-]{7,20}$/, message: '请输入正确的电话格式', trigger: 'blur' }
        ]
      }
    })
    
    // 业务设置
    const businessFormRef = ref(null)
    const businessFormState = reactive({
      businessForm: {
        maxDailyTickets: 300,
        startTime: new Date(2023, 0, 1, 8, 30),
        endTime: new Date(2023, 0, 1, 17, 30),
        workDays: ['1', '2', '3', '4', '5'],
        enableFaceRecognition: true,
        faceMatchThreshold: 80,
        ticketIntervalMinutes: 30,
        callTimeoutMinutes: 5
      },
      businessRules: {
        maxDailyTickets: [
          { required: true, message: '请输入每日最大叫号人数', trigger: 'blur' }
        ],
        ticketIntervalMinutes: [
          { required: true, message: '请输入重复取号限制时间', trigger: 'blur' }
        ],
        callTimeoutMinutes: [
          { required: true, message: '请输入叫号等待超时时间', trigger: 'blur' }
        ]
      }
    })
    
    // 短信设置
    const smsFormRef = ref(null)
    const smsFormState = reactive({
      smsForm: {
        enableSms: true,
        smsProvider: 'aliyun',
        accessKey: 'LTAI4G*********',
        accessSecret: '********',
        signName: '智能排队系统',
        ticketTemplateId: 'SMS_123456789',
        callTemplateId: 'SMS_987654321',
        testPhone: '13900000000'
      },
      smsRules: {
        smsProvider: [
          { required: true, message: '请选择短信服务提供商', trigger: 'change' }
        ],
        accessKey: [
          { required: true, message: '请输入AccessKey', trigger: 'blur' }
        ],
        accessSecret: [
          { required: true, message: '请输入AccessSecret', trigger: 'blur' }
        ],
        signName: [
          { required: true, message: '请输入短信签名', trigger: 'blur' }
        ],
        ticketTemplateId: [
          { required: true, message: '请输入取号成功模板ID', trigger: 'blur' }
        ],
        callTemplateId: [
          { required: true, message: '请输入叫号通知模板ID', trigger: 'blur' }
        ],
        testPhone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ]
      }
    })
    
    // 备份设置
    const backupFormRef = ref(null)
    const backupFormState = reactive({
      backupForm: {
        enableAutoBackup: true,
        backupFrequency: 'daily',
        backupTime: new Date(2023, 0, 1, 2, 0),
        maxBackupCount: 7
      },
      backupRecords: [
        {
          id: 1,
          fileName: 'facequeue_backup_20230610020000.sql',
          createTime: '2023-06-10 02:00:00',
          fileSize: '2.5 MB',
          type: 'auto'
        },
        {
          id: 2,
          fileName: 'facequeue_backup_20230609020000.sql',
          createTime: '2023-06-09 02:00:00',
          fileSize: '2.4 MB',
          type: 'auto'
        },
        {
          id: 3,
          fileName: 'facequeue_backup_20230608020000.sql',
          createTime: '2023-06-08 02:00:00',
          fileSize: '2.3 MB',
          type: 'auto'
        },
        {
          id: 4,
          fileName: 'facequeue_backup_20230607143025.sql',
          createTime: '2023-06-07 14:30:25',
          fileSize: '2.2 MB',
          type: 'manual'
        },
        {
          id: 5,
          fileName: 'facequeue_backup_20230607020000.sql',
          createTime: '2023-06-07 02:00:00',
          fileSize: '2.1 MB',
          type: 'auto'
        }
      ]
    })
    
    // 图片上传相关
    const beforeLogoUpload = (file) => {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG && !isPNG) {
        ElMessage.error('上传Logo只能是JPG或PNG格式!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('上传Logo大小不能超过2MB!')
        return false
      }
      
      return true
    }
    
    const handleLogoUpload = (options) => {
      const file = options.file
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        basicFormState.basicForm.logoUrl = reader.result
        ElMessage.success('Logo上传成功')
      }
    }
    
    // 保存设置
    const saveBasicSettings = () => {
      basicFormRef.value.validate((valid) => {
        if (valid) {
          ElMessage.success('基本设置保存成功')
        }
      })
    }
    
    const saveBusinessSettings = () => {
      businessFormRef.value.validate((valid) => {
        if (valid) {
          ElMessage.success('业务设置保存成功')
        }
      })
    }
    
    const saveSmsSettings = () => {
      smsFormRef.value.validate((valid) => {
        if (valid) {
          ElMessage.success('短信设置保存成功')
        }
      })
    }
    
    const saveBackupSettings = () => {
      ElMessage.success('备份设置保存成功')
    }
    
    // 重置表单
    const resetBasicForm = () => {
      basicFormRef.value.resetFields()
    }
    
    const resetBusinessForm = () => {
      businessFormRef.value.resetFields()
    }
    
    const resetSmsForm = () => {
      smsFormRef.value.resetFields()
    }
    
    const resetBackupForm = () => {
      backupFormRef.value.resetFields()
    }
    
    // 格式化匹配阈值
    const formatThreshold = (val) => {
      return `${val}%`
    }
    
    // 短信测试
    const testTicketSms = () => {
      if (!smsFormState.smsForm.testPhone) {
        ElMessage.warning('请输入测试手机号')
        return
      }
      
      ElMessage.success(`已向 ${smsFormState.smsForm.testPhone} 发送取号短信测试`)
    }
    
    const testCallSms = () => {
      if (!smsFormState.smsForm.testPhone) {
        ElMessage.warning('请输入测试手机号')
        return
      }
      
      ElMessage.success(`已向 ${smsFormState.smsForm.testPhone} 发送叫号短信测试`)
    }
    
    // 备份相关
    const createManualBackup = () => {
      const now = new Date()
      const timeStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`
      const fileName = `facequeue_backup_${timeStr}.sql`
      const maxId = Math.max(...backupFormState.backupRecords.map(item => item.id), 0)
      
      backupFormState.backupRecords.unshift({
        id: maxId + 1,
        fileName,
        createTime: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`,
        fileSize: '2.6 MB',
        type: 'manual'
      })
      
      ElMessage.success('手动备份创建成功')
    }
    
    const downloadBackup = (row) => {
      ElMessage.success(`正在下载备份文件: ${row.fileName}`)
    }
    
    const deleteBackup = (row) => {
      ElMessageBox.confirm(`确定要删除备份文件 ${row.fileName} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = backupFormState.backupRecords.findIndex(item => item.id === row.id)
        if (index !== -1) {
          backupFormState.backupRecords.splice(index, 1)
          ElMessage.success('备份文件删除成功')
        }
      }).catch(() => {})
    }
    
    onMounted(() => {
      // 页面加载时不需要额外操作
    })
    
    return {
      activeTab,
      basicFormRef,
      ...toRefs(basicFormState),
      businessFormRef,
      ...toRefs(businessFormState),
      smsFormRef,
      ...toRefs(smsFormState),
      backupFormRef,
      ...toRefs(backupFormState),
      beforeLogoUpload,
      handleLogoUpload,
      saveBasicSettings,
      saveBusinessSettings,
      saveSmsSettings,
      saveBackupSettings,
      resetBasicForm,
      resetBusinessForm,
      resetSmsForm,
      resetBackupForm,
      formatThreshold,
      testTicketSms,
      testCallSms,
      createManualBackup,
      downloadBackup,
      deleteBackup
    }
  }
}
</script>

<style scoped>
.settings-container {
  padding: 15px 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.settings-tabs {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  padding: 20px;
}

.settings-form-container {
  padding: 20px 0;
}

.settings-form {
  max-width: 800px;
}

.avatar-uploader {
  width: 120px;
  height: 40px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 40px;
  display: block;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
}

.form-tip {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

.time-separator {
  margin: 0 10px;
}
</style> 